package com.example.javalib.math;

/**
 * @Description: 翻转链表
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/1/21 17:33
 */
public class LinkReverseList {

    public static  class ListNode {

        int value;
        ListNode next = null;

        public ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        public ListNode(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {

        ListNode listNode5 = new ListNode(5, null);
        ListNode listNode4 = new ListNode(4, listNode5);
        ListNode listNode3 = new ListNode(3, listNode4);
        ListNode listNode2 = new ListNode(2, listNode3);
        ListNode head = new ListNode(1, listNode2);

        ListNode prev = iterate(head);
        ListNode prev2 = recursion(head);
        ListNode prev3 = reverseLinkedList(head);
//        System.out.println(prev);
        System.out.println(prev2);
        System.out.println(prev3);

    }

    //方法1： 迭代
    public static ListNode iterate(ListNode head) {
        ListNode prev = null, cur, next;
        cur = head;
        while (cur != null) {
            next = cur.next;//保存指针
            cur.next = prev;// 元素翻转

            prev = cur; //
            cur = next;
        }
        return prev;
    }
    //方法1：重复将首节点的下一个节点调整到最前面，如链表1->2->3->4，
    // 调整过程为2->1->3->4，3->2->1->4，4->3->2->1
    public static ListNode reverseLinkedList(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode p = new ListNode(-1);  //拟1个头节点
        p.next = head;
        ListNode nextNode = head.next;
        while (nextNode != null){
            //后一个节点调整到最前
            head.next = nextNode.next;
            nextNode.next = p.next;
            p.next = nextNode;
            nextNode = head.next;
        }
        return p.next;
    }

    //方法2 递归 使链表从尾节点开始指向前一个节点
    public static ListNode recursion(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode new_head = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return new_head;
    }
}
